import os
import cgi
import time
import logging
import datetime
import wsgiref.handlers
from urllib import urlencode, quote as urlquote
from demjson import decode as decode_json

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api.urlfetch import fetch, GET, POST

def get_all_friends(screen_name):
    """twitter api get friends - returns dict with allfriends"""
    allfriends = {}
    next_cursor=-1
    url = "http://api.twitter.com/1/statuses/friends.json?cursor="+str(next_cursor)+"&screen_name="+screen_name
    request = fetch(url)
    friends = decode_json(request.content)
    next_cursor = friends['next_cursor']
    for user in friends['users']:
        allfriends[user['screen_name']]=user['profile_image_url']
    while next_cursor:
        url = "http://api.twitter.com/1/statuses/friends.json?cursor="+str(next_cursor)+"&screen_name="+screen_name
        request = fetch(url)
        friends = decode_json(request.content)
        for user in friends['users']:
            allfriends[user['screen_name']]=user['profile_image_url']
        next_cursor = friends['next_cursor']
    return allfriends

def get_all_connections(screen_name):
    """GET ALL TWITTER's CONNECTIONS FOR screen_name"""
    allconnections = {}
    next_cursor = -1
    friends_url = "http://api.twitter.com/1/statuses/friends.json?cursor="+str(next_cursor)+"&screen_name="+screen_name
    followers_url = "http://api.twitter.com/1/statuses/followers.json?cursor="+str(next_cursor)+"&screen_name="+screen_name
    #GETTING ALL FOLLOWERS
    followers_request = fetch(followers_url)
    followers = decode_json(followers_request.content)
    if followers_request.status_code == 200:
        followers_next_cursor = followers['next_cursor']
        logging.info(str(time.time())+" "+followers_request.content)
    else:
        logging.error(str(time.time())+" Error: "+str(followers_request.status_code)+" "+followers_request.content)
    for user in followers['users']:
        allconnections[user['screen_name']]=user['profile_image_url']
    while followers_next_cursor:
        followers_url = "http://api.twitter.com/1/statuses/followers.json?cursor="+str(followers_next_cursor)+"&screen_name="+screen_name
        followers_request = fetch(followers_url)
        if followers_request.status_code == 200:
            logging.info(str(time.time())+" Getting All Followers for "+screen_name)
            followers = decode_json(followers_request.content)
            for user in followers['users']:
                allconnections[user['screen_name']]=user['profile_image_url']
            followers_next_cursor = followers['next_cursor']
        else:
            logging.error(str(time.time())+" Error: "+str(followers_request.status_code)+" "+followers_request.content)
    #GETTING ALL FRIENDS
    friends_request = fetch(friends_url)
    friends = decode_json(friends_request.content)
    if friends_request.status_code == 200:
        friends_next_cursor = friends['next_cursor']
    else:
        logging.error(str(time.time())+" Error: "+str(friends_request.reponse_code)+" "+friends_request.content)
    for user in friends['users']:
        allconnections[user['screen_name']]=user['profile_image_url']
    while friends_next_cursor:
        friends_url = "http://api.twitter.com/1/statuses/friends.json?cursor="+str(friends_next_cursor)+"&screen_name="+screen_name
        friends_request = fetch(friends_url)
        if friends_request.status_code == 200:
            logging.info(str(time.time())+" Getting All Friends for "+screen_name)
            friends = decode_json(friends_request.content)
            for user in friends['users']:
                allconnections[user['screen_name']]=user['profile_image_url']
            friends_next_cursor = friends['next_cursor']
        else:
            logging.error(str(time.time())+" Error: "+str(friends_request.status_code)+" "+friends_request.content)
    return allconnections

def encode(text):
    return urlquote(str(text), '')

class PrintEnvironmentHandler(webapp.RequestHandler):
    def get(self):
        for name in os.environ.keys():
            self.response.out.write("%s = %s<br />\n" % (name, os.environ[name]))

class getTweetByID(webapp.RequestHandler):
    def post(self):
        ids = self.request.get("ids")
        if ids == "":
            self.response.out.write("<!DOCTYPE HTML PUBLIC><!-- "+ids+" -->")
            self.response.out.write("""
<html><body><form action="/" method="post">
  <div><textarea name="ids" rows="400" cols="640"></textarea>
  <input type="submit" value="Submit"></div>
</form></body></html>""")
        else:
            pass

class MainHandler(webapp.RequestHandler):
    def get(self):
        screen_name = self.request.get("screen_name")
        if screen_name == "":
            self.response.out.write("<!DOCTYPE HTML PUBLIC><!-- "+screen_name+" -->")
            self.response.out.write("""<html><body><form action="/" method="post">
  <div><textarea name="screen_name" rows="1" cols="30"></textarea>
  <input type="submit" value="Screen Name"></div>
</form></body></html>""")
        else:
            users = get_all_connections(screen_name)
            for u,thumb in users.items():
                self.response.out.write("<a href=\"http://twitter.com/%s\"><img border=\"0\" alt=\"%s\" src=\"%s\" width=48 height=48></a>" % (u,u,thumb))

    def post(self):
        screen_name = self.request.get("screen_name")
        if screen_name == "":
            self.response.out.write("<!DOCTYPE HTML PUBLIC><!-- "+screen_name+" -->")
            self.response.out.write("""<html><body><form action="/" method="post">
  <div><textarea name="screen_name" rows="1" cols="30"></textarea>
  <input type="submit" value="Screen Name"></div>
</form></body></html>""")
        else:
            users = get_all_connections(screen_name)
            for u,thumb in users.items():
                self.response.out.write("<a href=\"http://twitter.com/%s\"><img border=\"0\" alt=\"%s\" src=\"%s\" width=48 height=48></a>" % (u,u,thumb))

# MAIN
def main():
    application = webapp.WSGIApplication(
                                         [('/env',PrintEnvironmentHandler),
                                         ('/ids/',getTweetByID),
                                         ('/', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
